/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sync.services;

import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

/**
 *
 * @author yarden
 */
public class SchemaParser {
     public static final String SCHEMA_TAG  = "schema";
     
    private XMLEventReader reader;
    private XMLEvent event;
    
    public String parse(InputStream input) {
        XMLInputFactory factory = getFactory();
        StringBuilder builder = new StringBuilder();
        
        try {
            reader = factory.createXMLEventReader(input);
            
            while (reader.hasNext()) {
                event = reader.nextEvent();
                if (event.isStartElement()) {
                    StartElement start = event.asStartElement();
                    String name = start.getName().getLocalPart();
                    
                    if (name.equals(SCHEMA_TAG)) {
                        // skip characters
                        while (reader.hasNext()) {
                            event = reader.nextEvent();
                            if (!event.isCharacters())
                                break;
                        }
                        while (!event.isEndElement() || !event.asEndElement().getName().getLocalPart().equals(SCHEMA_TAG)) {
                            builder.append(event.toString());
                            if (reader.hasNext())
                                event = reader.nextEvent();
                            else
                                break;
                        }
                    }
                }
            }
        } catch (XMLStreamException e) {
            Logger.getLogger(AssignmentItemParser.class.getName()).log(Level.SEVERE, "While reading server response", e);
        }
        
        return builder.toString();
        //return new Scanner(input).useDelimiter("\\A").next();
    }
    
     
    private XMLInputFactory getFactory() {
        XMLInputFactory factory = null;
        try {
            factory = XMLInputFactory.newInstance();
            factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
            factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
            factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
            factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        } catch (Exception e) {
            Logger.getLogger(AssignmentsParser.class.getName()).log(Level.SEVERE, null, e);
        }
        return factory;
    }
}
